package org.dromara.common.web.config

import cn.hutool.core.date.DateUtil
import org.dromara.common.core.utils.ObjectUtils
import org.dromara.common.web.handler.GlobalExceptionHandler
import org.dromara.common.web.interceptor.PlusWebInvokeTimeInterceptor
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.core.convert.converter.Converter
import org.springframework.format.FormatterRegistry
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
import org.springframework.web.filter.CorsFilter
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
import java.util.*

/**
 * 通用配置
 *
 * @author LikeYouDo
 * @date 2025/07/26
 */
@AutoConfiguration
class ResourcesConfig : WebMvcConfigurer {
    override fun addInterceptors(registry: InterceptorRegistry) {
        // 全局访问性能拦截
        registry.addInterceptor(PlusWebInvokeTimeInterceptor())
    }

    override fun addFormatters(registry: FormatterRegistry) {
        // 全局日期格式转换配置
        registry.addConverter(String::class.java, Date::class.java) { source ->
            val parse = DateUtil.parse(source) ?: return@addConverter null
            parse.toJdkDate()
        }
    }

    override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
    }

    /**
     * 跨域配置
     */
    @Bean
    fun corsFilter(): CorsFilter {
        val config = CorsConfiguration()
        config.allowCredentials = true
        // 设置访问源地址
        config.addAllowedOriginPattern("*")
        // 设置访问源请求头
        config.addAllowedHeader("*")
        // 设置访问源请求方法
        config.addAllowedMethod("*")
        // 有效期 1800秒
        config.maxAge = 1800L
        // 添加映射路径，拦截一切请求
        val source = UrlBasedCorsConfigurationSource()
        source.registerCorsConfiguration("/**", config)
        // 返回新的CorsFilter
        return CorsFilter(source)
    }

    /**
     * 全局异常处理器
     */
    @Bean
    fun globalExceptionHandler(): GlobalExceptionHandler {
        return GlobalExceptionHandler()
    }
}
